package com.ruoyi.security.service;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.security.common.R;
import com.ruoyi.security.mapper.UserMapper;
import com.ruoyi.security.model.SysUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.UserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import sun.misc.MessageUtils;

@RequiredArgsConstructor
@Slf4j
@Service
public class LoginService {


    @Autowired
    private final UserMapper userMapper;


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public R login(String username, String password, String code, String uuid) {
        //省略验证码开关
//        boolean captchaEnabled = configService.selectCaptchaEnabled();
//        // 验证码开关
//        if (captchaEnabled) {
//            validateCaptcha(username, code, uuid);
//        }
//        R user = loadUserByUsername(username);
        return  loadUserByUsername(username,password);
//        checkLogin(LoginType.PASSWORD, username, () -> !BCrypt.checkpw(password, user.getPassword()));
//        // 此处可根据登录用户的数据不同 自行创建 loginUser
//        LoginUser loginUser = buildLoginUser(user);
//        // 生成token
//        LoginHelper.loginByDevice(loginUser, DeviceType.PC);
//
//        recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
//        recordLoginInfo(user.getUserId(), username);
//        return StpUtil.getTokenValue();
    }


    public R loadUserByUsername(String username,String password) {
        SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
            .select(SysUser::getUserName, SysUser::getStatus)
            .eq(SysUser::getUserName, username));
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            return R.error("登录用户不存在");
        } else if ("1".equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            return R.error( "登录用户："+username +"已被停用");
        } else if(!BCrypt.checkpw(password, user.getPassword())){
            //匹配密码不成功
            return R.error("错误请重新输入");
        }
        //身份验证成功

        return R.ok(user);
    }
}
